var moment = require('moment');
var Model = require('./model.js')('klps');
var passwordLevel = require('./util.js').passwordLevel;
var crypt = require('crypto');
var async = require('async');
var base64url = require('base64url');

var validator = require('validator')

var KLPS = function(app) {
    var jwt = app.jwt;
    var token;
    this.authentication = function(req, res, next) {
        if (req.cookies["0321D43C384063E6FED635D736890B72"].token === token) {
            next();
        } else {
            res.redirect('login')
        }
    }
    this.login = function(req, res, next) {
        var user = req.body;
        var md5 = crypt.createHash("md5");
        md5.update(user.password)
        user.password = md5.digest('hex')
        async.waterfall([
            function(cb) {
                Model.findOne({
                    username: user.username,
                    password: user.password
                }, function(err, result) {
                    if (err) {
                        cb(new Error(err))
                    } else {
                        cb(null, result)
                    }
                })
            },
            //返回cookies
            function(user, cb) {
                var header = base64url(JSON.stringify(jwt.header));
                var payload = base64url(JSON.stringify(jwt.payload));
                var sha256 = crypt.createHmac('sha1', jwt.SecrectKey)
                var signature = sha256.update(header + "." + payload).digest().toString("base64");
                token = header + "." + payload + "." + signature;
                res.cookie("0321D43C384063E6FED635D736890B72", { user: user, token: token }, { maxAge: 30 * 60 * 1000, path: "/", httpOnly: true });
                cb(null);
            }
        ], function(err, result) {
            if (err) {
                console.log("登录失败:" + err)
                res.render('login')
            } else {
                console.log("登录成功")
                next()
            }
        });
        // 与数据库数据对比，校验用户信息的真实性
    }
    this.logout = function(req, res, next) {
        res.clearCookie("0321D43C384063E6FED635D736890B72");
        next();
    }
    this.register = function(req, res, next) {
        var user = req.body

        if (!validator.isEmail(user.email) || validator.isEmpty(user.email)) {
            res.status(501).send('请输入正确的email')
            return false
        }
        if (validator.isEmpty(user.username)) {
            res.status(502).send('用户名不能为空')
            return false
        }

        if (passwordLevel(user.password) < 4) {
            res.status(503).send('密码必须含有大小写字母、数字和特殊符号')
            return false
        }
        //加密密码
        var md5 = crypt.createHash("md5")
        md5.update(user.password)
        user.password = md5.digest('hex')
        user.createTime = moment().format('YYYY-MM-DD HH:mm:ss')

        var entity = new Model(user)
        entity.save(function(err) {
            if (err) {
                console.log(err)
            } else {
                console.log('注册成功')
                next()
            }
        })
    }
}

module.exports = KLPS